﻿Imports System.ComponentModel
Imports System.Collections.Concurrent
Imports System.Text
Imports Microsoft.Win32
Imports MostRecentlyUsed.MRUItems

Namespace Controls
    Public Class ctlOpenRecentProjects
        Private m_bAscending As Boolean = True
        Private m_iCurrentColumn As Integer

        Enum ProjectsColumnPosition
            Number
            ProjectName
            ProjectPath
        End Enum

        Private ReadOnly m_oIconCache As New Dictionary(Of String, Integer)()

        Private Sub ctlOpenRecentProjects_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            Try
                Dim szDefault As String = My.Settings.VSVersion

                If (String.IsNullOrWhiteSpace(szDefault)) Then szDefault = String.Empty

                Dim aszParts As String() = szDefault.Split("|".ToCharArray(), 2, StringSplitOptions.RemoveEmptyEntries)

                If (aszParts.Length > 0) Then
                    If (aszParts.Length > 1) Then
                        If (String.Compare("file", aszParts(1), True) = 0) Then
                            optFile.Checked = True
                        Else
                            optProjects.Checked = True
                        End If
                    End If

                    For iPos = 0 To cbVSVersions.Items.Count
                        If (String.Compare(aszParts(0), Convert.ToString(cbVSVersions.Items(iPos))) = 0) Then
                            cbVSVersions.SelectedItem = cbVSVersions.Items(iPos)
                            Exit For
                        End If
                    Next
                End If

                If (cbVSVersions.Items.Count > 0) Then
                    Show()

                    If (cbVSVersions.SelectedIndex < 0) Then cbVSVersions.SelectedIndex = 0
                End If

            Catch oExp As Exception
                Helper.DisplayException(oExp, Me, "Exception Loading Recent Projects Control")
            End Try
        End Sub

        Private Sub cbVSVersions_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbVSVersions.SelectedIndexChanged
            Try
                If (optProjects.Checked) Then
                    BindList(lstProjects, Helper.RecentType.Project)
                Else
                    BindList(lstProjects, Helper.RecentType.File)
                End If
            Catch
            End Try
        End Sub

        Private Sub BindList(lstItems As ListView, eRecentItemType As Helper.RecentType)
            Try
                ' The form is not fully loaded yet, so we cannot bind
                If (cbVSVersions.SelectedIndex < 0) Then Return

                lstItems.Items.Clear()
                m_oIconCache.Clear()
                m_oIconImageList.Images.Clear()

                Dim szMRUPath As String = If(eRecentItemType = Helper.RecentType.Project, GetProjectMRUPath(), GetFileMRUPath())

                Dim oVSProjectMRUList As List(Of VSProjectMRUItem) = Helper.GetMRUList(Of VSProjectMRUItem)(Helper.ProjectType.VisualStudio, eRecentItemType, szMRUPath,
                                                                                                            cbVSVersions.Text.Trim().ToUpper())
                Dim iPos As Integer = 1
                For Each oVSProjectMRUItem As VSProjectMRUItem In oVSProjectMRUList
                    'bool bPinned = false;
                    Try
                        Dim oInfo As New FileInfo(oVSProjectMRUItem.Path)

                        'New
                        Dim oNumberItem As New ListViewItem()
                        oNumberItem.Text = iPos.ToString()
                        oNumberItem.Tag = oVSProjectMRUItem.Name
                        oNumberItem.ImageIndex = GetIconIndex(oVSProjectMRUItem.Path)
                        oNumberItem.StateImageIndex = oNumberItem.ImageIndex
                        Dim oProject As New ListViewItem.ListViewSubItem(oNumberItem, oInfo.Name)
                        oProject.Tag = oVSProjectMRUItem.Name
                        Dim oPath As New ListViewItem.ListViewSubItem(oNumberItem, oVSProjectMRUItem.Path)
                        oNumberItem.SubItems.Add(oProject)
                        oNumberItem.SubItems.Add(oPath)
                        lstItems.Items.Add(oNumberItem)

                        iPos += 1
                        'don't throw any exceptions
                    Catch oExp As Exception
                        If (Debugger.IsAttached) Then
                            Helper.DisplayException(oExp, Me, "Error Binding List")
                        End If
                    End Try
                Next
                If oVSProjectMRUList.Count = 0 Then
                    lstItems.SmallImageList = Nothing

                    Dim oListItem As New ListViewItem()
                    oListItem.Text = String.Format("You have no recent {0}s.", eRecentItemType)
                    oListItem.SubItems.Add(String.Empty)
                    lstItems.Items.Add(oListItem)
                Else
                    lstItems.SmallImageList = m_oIconImageList
                End If
            Catch oExp As Exception
                If (Debugger.IsAttached) Then
                    Helper.DisplayException(oExp, Me, "Error Binding List")
                End If
            Finally
                lstItems.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent)
                If lstItems.Items.Count > 0 Then
                    lstItems.Items(0).Selected = True
                End If
                lstItems.Focus()
            End Try
        End Sub

        Private Function GetIconIndex(szPath As String) As Integer
            Dim iNum As Integer
            Dim oInfo As New FileInfo(szPath)
            Dim szExtension As String = oInfo.Extension.ToLower()
            If m_oIconCache.ContainsKey(szExtension) Then
                Return m_oIconCache(szExtension)
            End If
            AddPathIcon(szPath)
            iNum = m_oIconImageList.Images.Count - 1
            m_oIconCache.Add(szExtension, iNum)
            Return iNum
        End Function

        Private Function GetRecentType() As Helper.RecentType
            If (optFile.Checked) Then Return Helper.RecentType.File

            Return Helper.RecentType.Project
        End Function

        Private Sub AddPathIcon(szFilePath As String)
            Try
                Dim oAssociatedIcon As Icon = Nothing
                Try
                    oAssociatedIcon = Interop.GetAssociatedIcon(szFilePath)
                Catch
                End Try
                If oAssociatedIcon IsNot Nothing Then
                    Dim oImage As Bitmap = oAssociatedIcon.ToBitmap()
                    Dim oBitmap2 As New Bitmap(&H12, &H10)
                    Graphics.FromImage(oBitmap2).DrawImageUnscaled(oImage, New Point(2, 0))
                    m_oIconImageList.Images.Add(oBitmap2)
                End If
            Catch
            End Try
        End Sub

        Private Function GetProjectMRUPath() As String
            Return String.Format("{0}\ProjectMRUList", GetVisualStudioRoot())
        End Function

        Private Function GetFileMRUPath() As String
            Return String.Format("{0}\FileMRUList", GetVisualStudioRoot())
        End Function

        Private Function GetVisualStudioRoot() As String
            Return String.Format("{0}\{1}", Constants.VS_REG_VALUE_NAME, GetVisualStudioVersion())
        End Function

        Private Function GetVisualStudioVersion() As String
            Dim szVersion As String
            Select Case cbVSVersions.Text.Trim().ToUpper()
                Case "2002"
                    szVersion = "7.0"
                    Exit Select
                Case "2003"
                    szVersion = "7.1"
                    Exit Select
                Case "2005"
                    szVersion = "8.0"
                    Exit Select
                Case "2008"
                    szVersion = "9.0"
                    Exit Select
                Case "2010"
                    szVersion = "10.0"
                    Exit Select
                Case "2012"
                    szVersion = "11.0"
                Case "2013"
                    szVersion = "12.0"
                    Exit Select
                Case Else
                    Throw New ApplicationException(String.Format("Unmapped Visual Studio version found: {0}", cbVSVersions.Text))
            End Select
            Return szVersion
        End Function

        Private Sub pbRecentConfiguration_Click(sender As Object, e As EventArgs) Handles pbRecentConfiguration.Click
            Try
                Using ofrmRecentConfig As frmRecentConfiguration = New frmRecentConfiguration(Helper.ProjectType.VisualStudio)
                    ofrmRecentConfig.ShowDialog(Me)
                End Using
            Catch oExp As Exception
                Helper.DisplayException(oExp, Me, "Exception Setting Recent Configuration")
            End Try
        End Sub

        Private Sub OpenProjectsToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OpenProjectsToolStripMenuItem.Click
            Try
                Dim oParent As frmMain = ParentForm
                If (oParent.IsOpenRecentProjectsTabSelected And (lstProjects.SelectedItems.Count > 0)) Then
                    OpenProjects()

                    oParent.CloseIfNoShift()
                End If
            Catch oExp As Exception
                Helper.DisplayException(oExp, Me, "Exception Opening Selected Project(s)")
            End Try
        End Sub

        Private Sub OpenProjects()
            For Each oItem As ListViewItem In lstProjects.SelectedItems
                Dim szProject As String = oItem.SubItems(ProjectsColumnPosition.ProjectPath).Text
                Helper.OpenFile(szProject)
            Next
        End Sub

        Private Sub openContainingDirectoryToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles openContainingDirectoryToolStripMenuItem.Click
            Try
                Dim oParent As frmMain = ParentForm
                If (oParent.IsOpenRecentProjectsTabSelected And (lstProjects.SelectedItems.Count > 0)) Then
                    OpenContainingDirectories()
                    oParent.CloseIfNoShift()
                End If
            Catch oExp As Exception
                Helper.DisplayException(oExp, Me, "Exception Opening Containing Directory")
            End Try
        End Sub

        Private Sub openSourceControlToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles openSourceControlToolStripMenuItem.Click
            Try
                'Dim oParent As frmMain = Me.ParentForm
                'If (oParent.IsOpenRecentProjectsTabSelected And (lstProjects.SelectedItems.Count <> 1)) Then Exit Sub

                'Dim oItem As ListViewItem = lstProjects.SelectedItems(0)
                'Dim szPath As String = oItem.SubItems(ProjectsColumnPosition.ProjectPath).Text

                'oParent.CloseIfNoShift()
            Catch oExp As Exception
                Helper.DisplayException(oExp, Me, "Exception Opening Source Control Directory")
            End Try
        End Sub

        Private Sub openCodeFiletoolStripMenuItem_DropDownOpening(sender As Object, e As EventArgs) Handles openCodeFiletoolStripMenuItem.DropDownOpening
            Try
                Dim oParent As frmMain = ParentForm

                If (Not oParent.IsOpenRecentProjectsTabSelected) Or (lstProjects.SelectedItems.Count <> 1) Then Exit Sub
                If (optFile.Checked) Then Exit Sub

                Dim oItem As ListViewItem = lstProjects.SelectedItems(0)

                Dim oInfo As New FileInfo(oItem.SubItems(CInt(ProjectsColumnPosition.ProjectPath)).Text)
                Dim szDirectory As String = oInfo.Directory.FullName

                PopulateChildFileDropDownList(szDirectory, openCodeFiletoolStripMenuItem)
            Catch
            End Try
        End Sub

        Private Sub PopulateChildFileDropDownList(szDirectory As String, oParentMenuItem As ToolStripMenuItem)
            oParentMenuItem.DropDownItems.Clear()

            If Directory.Exists(szDirectory) Then

                'add strings to filterlist, these will return image files
                Dim oFilterList As List(Of String) = Helper.GetCodeFileExtensions(Helper.ProjectType.VisualStudio)

                Dim oDirectories As New ConcurrentBag(Of ToolStripMenuItem)()
                Parallel.ForEach(Directory.GetDirectories(szDirectory, "*", SearchOption.TopDirectoryOnly), Sub(szDir)
                                                                                                                Dim oDirInfo As New DirectoryInfo(szDir)
                                                                                                                Dim oNewChild As New ToolStripMenuItem(oDirInfo.Name, openContainingDirectoryToolStripMenuItem.Image)
                                                                                                                AddHandler oNewChild.DropDownOpening, AddressOf openChildFileToolStripMenuItem_DropDownOpening
                                                                                                                AddHandler oNewChild.MouseDown, AddressOf openChildFileToolStripMenuItem_MouseDown
                                                                                                                oNewChild.Tag = oDirInfo.FullName

                                                                                                                If ((Directory.GetDirectories(szDir, "*", SearchOption.TopDirectoryOnly).Length > 0)) OrElse (Helper.GetFilesInDirectory(szDirectory, oFilterList, True).Count > 0) _
                                                                                                                                Then
                                                                                                                    Dim oPlaceHolder As New ToolStripMenuItem("PlaceHolder")
                                                                                                                    oNewChild.DropDownItems.Add(oPlaceHolder)
                                                                                                                End If

                                                                                                                oDirectories.Add(oNewChild)
                                                                                                            End Sub)

                'oDirectories.OrderBy(Function(oKVP) oKVP.Key)
                Dim oMenuItems As List(Of ToolStripMenuItem) = oDirectories.ToList()
                oMenuItems.Sort(New CompareToolStripMenuItems())
                For Each oNewChild As ToolStripMenuItem In oMenuItems
                    oParentMenuItem.DropDownItems.Add(oNewChild)
                Next

                Dim oFiles As List(Of String) = Helper.GetFilesInDirectory(szDirectory, oFilterList)
                oFiles.Sort()
                For Each szFile As String In oFiles
                    Dim iIndex As Integer = GetIconIndex(szFile)
                    Dim oNewChild As New ToolStripMenuItem(Path.GetFileName(szFile), m_oIconImageList.Images(iIndex))
                    AddHandler oNewChild.MouseDown, AddressOf openChildFileToolStripMenuItem_MouseDown
                    oNewChild.Tag = szFile
                    oParentMenuItem.DropDownItems.Add(oNewChild)
                Next
            End If
        End Sub

        Private Sub ContextMenuStripProjects_Opening(sender As Object, e As CancelEventArgs) Handles ContextMenuStripProjects.Opening
            Try
                openSourceControlToolStripMenuItem.Visible = False
                openCodeFiletoolStripMenuItem.Visible = False

                Dim oParent As frmMain = ParentForm
                If (Not oParent.IsOpenRecentProjectsTabSelected) Or (lstProjects.SelectedItems.Count = 0) Then
                    e.Cancel = True
                    Exit Sub
                End If

                'If (lstProjects.SelectedItems.Count <> 1) Then
                '    Exit Sub
                'End If

                openCodeFiletoolStripMenuItem.Visible = File.Exists(My.Settings.TextEditorPath)

                RemoveHandler openCodeFiletoolStripMenuItem.MouseDown, AddressOf openChildFileToolStripMenuItem_MouseDown
                openCodeFiletoolStripMenuItem.DropDownItems.Clear()

                If (openCodeFiletoolStripMenuItem.Available) Then
                    If (optFile.Checked) Then
                        openCodeFiletoolStripMenuItem.Tag = lstProjects.SelectedItems(0).SubItems(ProjectsColumnPosition.ProjectPath).Text
                        AddHandler openCodeFiletoolStripMenuItem.MouseDown, AddressOf openChildFileToolStripMenuItem_MouseDown
                    Else
                        openCodeFiletoolStripMenuItem.Tag = String.Empty
                        openCodeFiletoolStripMenuItem.DropDownItems.Add("Placeholder")
                    End If
                End If
            Catch oExp As Exception
                Helper.DisplayException(oExp, Me, "Exception opening context menu")
            End Try
        End Sub

        Private Sub CopyToClipboard(sender As Object, e As EventArgs) _
            Handles copyToFileNameToolStripMenuItem.Click, copyToFilePathToolStripMenuItem.Click, copyToFilePathNameToolStripMenuItem.Click,
                    copyToFileNameWithoutExtentionToolStripMenuItem.Click
            Try
                Dim oParent As frmMain = ParentForm
                If oParent.IsOpenRecentProjectsTabSelected AndAlso (lstProjects.SelectedItems.Count > 0) Then
                    Dim oTextSB As New StringBuilder()
                    For Each oItem As ListViewItem In lstProjects.SelectedItems
                        Dim szProject As String = oItem.SubItems(CInt(ProjectsColumnPosition.ProjectPath)).Text

                        If copyToFileNameToolStripMenuItem.Equals(sender) Then
                            oTextSB.AppendLine(MRUFiles.GetFileInfo(szProject, MRUFileInfo.FileNameExtension))
                        ElseIf copyToFileNameWithoutExtentionToolStripMenuItem.Equals(sender) Then
                            oTextSB.AppendLine(MRUFiles.GetFileInfo(szProject, MRUFileInfo.FileName))
                        ElseIf copyToFilePathNameToolStripMenuItem.Equals(sender) Then
                            oTextSB.AppendLine(szProject)
                        ElseIf copyToFilePathToolStripMenuItem.Equals(sender) Then
                            oTextSB.AppendLine(MRUFiles.GetFileInfo(szProject, MRUFileInfo.Path))
                        End If
                    Next

                    If oTextSB.Length > 0 Then
                        Clipboard.SetText(oTextSB.ToString())
                    End If
                End If

                'oParent.CloseIfNoShift()
            Catch oExp As Exception
                Helper.DisplayException(oExp, Me, "Exception Copying Data To Clipboard")
            End Try
        End Sub

        Private Sub getLatestVersionOpenProjectsToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles getLatestVersionOpenProjectsToolStripMenuItem.Click
            Try
                Dim oParent As frmMain = ParentForm
                If oParent.IsOpenRecentProjectsTabSelected AndAlso (lstProjects.SelectedItems.Count > 0) Then
                    GetLatestVersions()
                    OpenProjects()
                    oParent.CloseIfNoShift()
                End If

            Catch oExp As Exception
                Helper.DisplayException(oExp, Me, "Exception Getting Latest Version")
            End Try
        End Sub

        Private Sub getLatestVersionOpenContainingDirectoryToolStripMenuItem1_Click(sender As Object, e As EventArgs) _
            Handles getLatestVersionOpenContainingDirectoryToolStripMenuItem1.Click
            Try
                Dim oParent As frmMain = ParentForm
                If oParent.IsOpenRecentProjectsTabSelected AndAlso (lstProjects.SelectedItems.Count > 0) Then
                    GetLatestVersions()
                    OpenContainingDirectories()
                    oParent.CloseIfNoShift()
                End If

            Catch oExp As Exception
                Helper.DisplayException(oExp, Me, "Exception Getting Latest Vesion")
            End Try
        End Sub

        Private Sub GetLatestVersions()
            For Each oItem As ListViewItem In lstProjects.SelectedItems
                Dim oInfo As New FileInfo(oItem.SubItems(CInt(ProjectsColumnPosition.ProjectPath)).Text)
                Dim szDirectory As String = oInfo.Directory.FullName
                If (optProjects.Checked) Then
                    Helper.GetLastestFromSourceControlDirectory(szDirectory, String.Empty)
                Else
                    Helper.GetLastestFromSourceControlDirectory(szDirectory, oInfo.Name)
                End If
            Next
        End Sub

        Private Sub OpenContainingDirectories()
            For Each oItem As ListViewItem In lstProjects.SelectedItems
                Dim oInfo As New FileInfo(oItem.SubItems(ProjectsColumnPosition.ProjectPath).Text)
                Helper.OpenDirectory(oInfo.Directory.FullName)
            Next
        End Sub

        Private Sub openChildFileToolStripMenuItem_DropDownOpening(sender As Object, e As EventArgs)
            Try
                Dim oChildMenuItem As ToolStripMenuItem = DirectCast(sender, ToolStripMenuItem)
                Dim szDirectory As String = oChildMenuItem.Tag.ToString()
                PopulateChildFileDropDownList(szDirectory, oChildMenuItem)
            Catch
            End Try
        End Sub

        Private Sub openChildFileToolStripMenuItem_MouseDown(sender As Object, e As MouseEventArgs)
            Try
                Dim oParent As frmMain = ParentForm

                If (Not oParent.IsOpenRecentProjectsTabSelected) Or (lstProjects.SelectedItems.Count <> 1) Then Exit Sub

                Dim oFileSenderMenuItem As ToolStripMenuItem = TryCast(sender, ToolStripMenuItem)
                If oFileSenderMenuItem IsNot Nothing Then
                    Dim szTag As String = oFileSenderMenuItem.Tag.ToString()
                    If e.Button = MouseButtons.Left Then
                        If File.Exists(szTag) Then
                            Using oProcess As New Process()
                                oProcess.StartInfo = New ProcessStartInfo(My.Settings.TextEditorPath)
                                oProcess.StartInfo.Arguments = szTag
                                oProcess.Start()
                                oParent.CloseIfNoShift()
                            End Using
                        Else
                            oFileSenderMenuItem.DropDownItems(0).Visible = True
                        End If
                    ElseIf e.Button = MouseButtons.Right Then
                        If Directory.Exists(szTag) Then
                            Using oProcess As New Process()
                                oProcess.StartInfo = New ProcessStartInfo(szTag)
                                oProcess.Start()
                                oParent.CloseIfNoShift()
                            End Using
                        End If
                    End If
                End If
            Catch
            End Try
        End Sub

        Private Class CompareToolStripMenuItems
            Implements IComparer(Of ToolStripMenuItem)
            ' Because the class implements IComparer, it must define a 
            ' Compare method. The method returns a signed integer that indicates 
            ' whether Item1 > Item2 (return is greater than 0), Item1 < Item2 (return is negative),
            ' or Item1 equals Item2 (return value is 0). This Compare method compares strings. 
            Public Function Compare(ByVal Item1 As ToolStripMenuItem, ByVal Item2 As ToolStripMenuItem) As Integer _
                Implements IComparer(Of ToolStripMenuItem).Compare
                Return String.Compare(Item1.Tag.ToString(), Item2.Tag.ToString(), True)
            End Function
        End Class

        Private Sub pbCancel_Click(sender As Object, e As EventArgs) Handles pbCancel.Click
            Try
                Dim oParent As frmMain = ParentForm
                oParent.Close()
            Catch
            End Try
        End Sub

        Private Sub pbOpen_Click(sender As Object, e As EventArgs) Handles pbOpen.Click
            Try
                OpenProjectsToolStripMenuItem_Click(sender, e)
            Catch oExp As Exception
                Helper.DisplayException(oExp, Me, "Exception Opening Selected Project(s)")
            End Try
        End Sub

        Private Sub pbDefault_Click(sender As Object, e As EventArgs) Handles pbDefault.Click
            Try
                Dim szType As String = If(optFile.Checked, "File", "Project")
                My.Settings.VSVersion = cbVSVersions.Text & "|" & szType
                My.Settings.Save()
            Catch oExp As Exception
                Helper.DisplayException(oExp, Me, "Exception Setting Default VS Version")
            End Try
        End Sub

        Private Sub clearProjectsFromListToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles clearProjectsFromListToolStripMenuItem.Click
            Try
                Dim szMRUPath As String = If(GetRecentType() = Helper.RecentType.Project, GetProjectMRUPath(), GetFileMRUPath())
                ClearCheckedKeys(cbVSVersions.Text.Trim().ToUpper(), szMRUPath, lstProjects)
                cbVSVersions_SelectedIndexChanged(sender, Nothing)
            Catch oExp As Exception
                Helper.DisplayException(oExp, Me, "Exception Setting Default VS Version")
            End Try
        End Sub

        Private Sub ClearCheckedKeys(szVisualStudioVersion As String, szRegPath As String, lstItems As ListView)
            Dim oKey As RegistryKey = Nothing
            Try
                If lstItems.SelectedItems.Count = 0 Then Return

                Dim oList As New List(Of ListViewItem)
                Dim oDictionary As New Dictionary(Of String, String)()
                oKey = Registry.CurrentUser.OpenSubKey(szRegPath, True)

                Dim aszValueNames As String() = Nothing
                If (oKey IsNot Nothing) Then
                    aszValueNames = oKey.GetValueNames()

                    'Get the items from the registry
                    For Each szName As String In aszValueNames
                        oDictionary.Add(szName, oKey.GetValue(szName).ToString())
                    Next
                End If

                Dim bItemRemovedFromRegistry As Boolean = False

                'Get the list of items to remove
                For Each oItem As ListViewItem In lstItems.SelectedItems
                    Dim oAdditionalVSProjectItems As RecentlyUsedItems = Helper.GetAdditionalProjectItems(Helper.ProjectType.VisualStudio, GetRecentType(), lstItems.Items.Count,
                                                                                                   szVisualStudioVersion)

                    Dim szTag As String = oItem.Tag.ToString()
                    If oDictionary.ContainsKey(szTag) Then
                        oAdditionalVSProjectItems.Remove(oDictionary(szTag))

                        bItemRemovedFromRegistry = True
                        oDictionary.Remove(szTag)
                    Else
                        If szTag = Constants.EXTENDED_MRU_ITEM Then
                            For Each szAdditionalVSProjectItem As String In oAdditionalVSProjectItems
                                If szAdditionalVSProjectItem.IndexOf(oItem.SubItems(2).Text, StringComparison.OrdinalIgnoreCase) >= 0 Then
                                    oAdditionalVSProjectItems.Remove(szAdditionalVSProjectItem)
                                    Exit For
                                End If
                            Next
                        Else
                            Helper.DisplayMessage(Me, String.Format("Unable to find tag '{0}' in extended history.", szTag), "Error Clearing Project")
                            Return
                        End If
                    End If
                    oList.Add(oItem)
                Next

                'Remove the items from the listview
                For Each oItem As ListViewItem In oList
                    lstItems.Items.Remove(oItem)
                Next

                If (bItemRemovedFromRegistry) And (aszValueNames IsNot Nothing) Then
                    'Now delete the items from the registry
                    For Each szName As String In aszValueNames
                        oKey.DeleteValue(szName)
                    Next

                    ' Now repopulate the items into the registry
                    Dim iNumber As Integer = 0
                    For Each szKey As String In oDictionary.Keys
                        iNumber += 1
                        oKey.SetValue(String.Format("File{0}", iNumber), oDictionary(szKey))
                    Next
                    oKey.Close()
                End If
            Catch
            Finally
                If oKey IsNot Nothing Then
                    oKey.Close()
                End If
            End Try
        End Sub

        Private Sub lstProjects_DoubleClick(sender As Object, e As EventArgs) Handles lstProjects.DoubleClick
            Try
                OpenProjectsToolStripMenuItem_Click(sender, e)
            Catch oExp As Exception
                Helper.DisplayException(oExp, Me, "Exception Opening Selected Project(s)")
            End Try
        End Sub

        Private Sub lstProjects_ColumnClick(sender As Object, e As ColumnClickEventArgs) Handles lstProjects.ColumnClick
            Try
                If e.Column = m_iCurrentColumn Then
                    m_bAscending = Not m_bAscending
                Else
                    m_bAscending = True
                End If

                ' Set the ListViewItemSorter property to a new ListViewItemComparer object.
                Dim eCompareType As ListViewItemComparer.CompareType
                If e.Column = CInt(ProjectsColumnPosition.Number) Then
                    eCompareType = ListViewItemComparer.CompareType.Int
                Else
                    eCompareType = ListViewItemComparer.CompareType.[String]
                End If
                lstProjects.ListViewItemSorter = New ListViewItemComparer(e.Column, m_bAscending, eCompareType)
                ' Call the sort method to manually sort.
                lstProjects.Sort()

                m_iCurrentColumn = e.Column
            Catch
            End Try
        End Sub

        Private Sub txtFilter_TextChanged(sender As Object, e As EventArgs) Handles txtFilter.TextChanged
            Try
                Dim szFilter As String = txtFilter.Text.Trim()
                If (lstProjects.Items.Count > 0) And (szFilter.Length >= 3) Then
                    lstProjects.SelectedItems.Clear()
                    For Each oItem As ListViewItem In lstProjects.Items
                        If (oItem.SubItems(2).Text.IndexOf(szFilter, StringComparison.OrdinalIgnoreCase) >= 0) Then
                            oItem.ForeColor = Color.Red
                            oItem.Checked = True
                        Else
                            oItem.Checked = False
                        End If
                    Next
                ElseIf (txtFilter.Text.Length = 0) Then
                    For Each oItem As ListViewItem In lstProjects.Items
                        oItem.Checked = False
                    Next
                End If
            Catch
            End Try
        End Sub

        Private Sub txtFilter_KeyUp(sender As Object, e As KeyEventArgs) Handles txtFilter.KeyUp
            Try
                If (e.KeyCode = Keys.Escape) Then
                    txtFilter.Clear()
                End If
            Catch
            End Try
        End Sub

        Private Sub lstProjects_ItemChecked(sender As Object, e As ItemCheckedEventArgs) Handles lstProjects.ItemChecked
            Try
                If (e.Item.Checked = True) Then
                    e.Item.ForeColor = Color.Red
                Else
                    e.Item.ForeColor = lstProjects.ForeColor
                End If
            Catch
            End Try
        End Sub

        Private Sub optFile_CheckedChanged(sender As Object, e As EventArgs) Handles optFile.CheckedChanged
            Try
                cbVSVersions_SelectedIndexChanged(sender, e)
            Catch
            End Try
        End Sub

        Private Sub openCodeFiletoolStripMenuItem_MouseDown(sender As Object, e As MouseEventArgs) Handles openCodeFiletoolStripMenuItem.MouseDown
            Try
                openChildFileToolStripMenuItem_MouseDown(sender, e)
            Catch
            End Try
        End Sub
    End Class
End Namespace